/*
 * User: ronma
 * Date: 06/01/2008
 *
 * Copyright (2005) IDI. All rights reserved.
 * This software is a proprietary information of Israeli Direct Insurance.
 * Created by IntelliJ IDEA.
 */
package com.idi.maven.plugins.poms;

import com.google.common.collect.MapMaker;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.jfrog.jade.plugins.common.injectable.MvnInjectableMojoSupport;
import org.jfrog.maven.annomojo.annotations.MojoGoal;
import org.jfrog.maven.annomojo.annotations.MojoParameter;
import org.jfrog.maven.annomojo.annotations.MojoRequiresDependencyResolution;

import java.util.*;
import java.util.concurrent.ConcurrentMap;

/**
 *
 */
@MojoGoal("trail")
@MojoRequiresDependencyResolution
public class Trail extends MvnInjectableMojoSupport {


    @MojoParameter(required = true,expression = "${bundleAnalyze}", defaultValue = "false")
    private String bundleAnalyze;

    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info("dependencyTrail:");
        getProject().getDependencyArtifacts();
        searchForDependenciesBundles(getProject().getDependencyManagement().getDependencies());
        for (final Artifact artifact : (Set<Artifact>) getProject().getArtifacts()) {
            final List<String> dependencyTrail = artifact.getDependencyTrail();
            getLog().info(String.format("%s:%s (scope: %s) :", artifact.getGroupId(), artifact.getArtifactId(), artifact.getScope()));
            getLog().info(String.format("\t%s", Arrays.deepToString(dependencyTrail.toArray()).replace(",", "->")));
        }
    }


    private void searchForDependenciesBundles(List<Dependency> dependencies) {
        final ConcurrentMap<String, Dependency> bundlesMap = new MapMaker().makeMap();
        for (Dependency dependency : dependencies) {
            if ((dependency.getScope() != null && dependency.getScope().equals(Artifact.SCOPE_PROVIDED))
                    && (dependency.getType() != null && dependency.getType().equals("jar"))) {
                final String bundleId = dependency.getGroupId() + "_" + dependency.getArtifactId() + "_" + dependency.getVersion();
                bundlesMap.put(bundleId, dependency);
            }
        }
        getLog().info("DependencyManagement holds = " + bundlesMap.values().size() + " bundles in scope");
    }


}